<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>编辑商品 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section>
        <h2>编辑商品</h2>

        <div class="card">
            <form id="editForm">
                <input type="hidden" id="productId">

                <div class="form-group">
                    <label for="name">商品名称 <span class="required">*</span></label>
                    <input type="text" id="name" name="name" required>
                </div>

                <div class="form-group">
                    <label for="description">商品描述</label>
                    <textarea id="description" name="description" rows="5"></textarea>
                </div>

                <div class="form-group">
                    <label for="price">价格 (元) <span class="required">*</span></label>
                    <input type="number" id="price" name="price" step="0.01" min="0.01" required>
                </div>

                <div class="form-group">
                    <label for="categoryId">商品分类</label>
                    <select id="categoryId" name="categoryId">
                        <option value="">-- 选择分类 --</option>
                        <!-- 分类将通过JavaScript加载 -->
                    </select>
                </div>

                <div class="form-group">
                    <label for="validUntil">有效期至 (留空表示永久有效)</label>
                    <input type="datetime-local" id="validUntil" name="validUntil">
                </div>

                <div class="form-group">
                    <label for="productImage">商品图片 (可选)</label>
                    <input type="file" id="productImage" name="productImage" accept="image/*">
                    <div class="image-preview-container">
                        <img id="imagePreview" class="hidden" alt="图片预览" />
                        <div id="currentImageContainer" class="hidden">
                            <p>当前图片：</p>
                            <img id="currentImage" alt="当前商品图片" />
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="imageUrl">商品图片URL (可选)</label>
                    <input type="url" id="imageUrl" name="imageUrl" placeholder="http://example.com/image.jpg">
                    <small>您可以上传图片或提供图片URL，如果两者都提供，将优先使用上传的图片</small>
                </div>

                <div class="form-group">
                    <label for="status">商品状态</label>
                    <select id="status" name="status" disabled>
                        <option value="pending">待审核</option>
                        <option value="on_sale">上架中</option>
                        <option value="off_sale">已下架</option>
                        <option value="sold">已售出</option>
                    </select>
                    <small>商品状态不可直接修改，请在我的商品页面使用上架/下架按钮</small>
                    <small class="warning-text">注意：编辑商品后，商品状态将重置为"待审核"，需要重新审核后才能上架</small>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn">保存修改</button>
                    <a href="/my-products" class="btn secondary">返回</a>
                </div>
            </form>
        </div>

        <div id="msg"></div>
    </section>
</div>
<script>
    // 获取URL参数
    function getQueryParam(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    // 加载分类数据
    async function loadCategories() {
        try {
            const res = await fetch('/api/categories');
            const categories = await res.json();

            const select = document.getElementById('categoryId');
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.id;
                option.textContent = category.name;
                select.appendChild(option);
            });
        } catch (e) {
            console.error('加载分类失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">加载分类失败，请刷新页面重试</div>';
        }
    }

    // 图片预览功能
    document.getElementById('productImage').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(event) {
                const imgPreview = document.getElementById('imagePreview');
                imgPreview.src = event.target.result;
                imgPreview.classList.remove('hidden');
                // 隐藏当前图片显示
                document.getElementById('currentImageContainer').classList.add('hidden');
            };
            reader.readAsDataURL(file);
        }
    });

    // 加载商品数据
    async function loadProduct() {
        const productId = getQueryParam('id');
        if (!productId) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">未指定商品ID，无法编辑</div>';
            return;
        }

        document.getElementById('productId').value = productId;

        try {
            const res = await fetch(`/api/products/${productId}`, {
                credentials: 'include'
            });

            const data = await res.json();

            if (data.error) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error}</div>`;
                return;
            }

            const product = data.product;

            // 填充表单数据
            document.getElementById('name').value = product.name || '';
            document.getElementById('description').value = product.description || '';
            document.getElementById('price').value = product.price || '';
            document.getElementById('imageUrl').value = product.imageUrl || '';
            document.getElementById('status').value = product.status || 'pending';

            // 设置分类
            if (product.category && product.category.id) {
                document.getElementById('categoryId').value = product.category.id;
            }

            // 设置有效期
            if (product.validUntil) {
                // 将ISO格式转换为本地datetime-local格式
                const date = new Date(product.validUntil);
                const localDatetime = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
                    .toISOString().slice(0, 16);
                document.getElementById('validUntil').value = localDatetime;
            }

            // 显示当前商品图片
            if (product.imageUrl) {
                const currentImage = document.getElementById('currentImage');
                currentImage.src = product.imageUrl;
                document.getElementById('currentImageContainer').classList.remove('hidden');
            }

        } catch (e) {
            console.error('加载商品数据失败:', e);
            document.getElementById('msg').innerHTML = '<div class="error-msg">加载商品数据失败，请刷新页面重试</div>';
        }
    }

    // 提交表单
    document.getElementById('editForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const msg = document.getElementById('msg');
        msg.innerHTML = '<div class="info-msg">正在处理，请稍候...</div>';

        const productId = document.getElementById('productId').value;

        // 获取表单数据
        const formData = new FormData(this);
        const productData = {
            name: formData.get('name'),
            description: formData.get('description'),
            price: parseFloat(formData.get('price')),
            imageUrl: formData.get('imageUrl') || null
        };

        // 处理分类
        if (formData.get('categoryId')) {
            productData.category = { id: parseInt(formData.get('categoryId')) };
        }

        // 处理有效期
        if (formData.get('validUntil')) {
            productData.validUntil = new Date(formData.get('validUntil')).toISOString();
        }

        try {
            // 先处理图片上传（如果有）
            const imageFile = document.getElementById('productImage').files[0];
            if (imageFile) {
                const imageFormData = new FormData();
                imageFormData.append('file', imageFile);

                const uploadRes = await fetch('/api/upload/image', {
                    method: 'POST',
                    credentials: 'include',
                    body: imageFormData
                });

                if (!uploadRes.ok) {
                    throw new Error('图片上传失败');
                }

                const uploadData = await uploadRes.json();
                if (uploadData.imageUrl) {
                    productData.imageUrl = uploadData.imageUrl;
                } else if (uploadData.error) {
                    throw new Error(uploadData.error);
                }
            }

            const res = await fetch(`/api/products/${productId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify(productData)
            });

            const data = await res.json();

            if (data.error) {
                msg.innerHTML = `<div class="error-msg">${data.error}</div>`;
            } else {
                msg.innerHTML = '<div class="success-msg">商品更新成功</div>';

                // 延迟跳转
                setTimeout(() => {
                    window.location.href = '/my-products';
                }, 2000);
            }
        } catch (e) {
            console.error('更新商品失败:', e);
            msg.innerHTML = `<div class="error-msg">更新失败: ${e.message}</div>`;
        }
    });

    // 页面加载时执行
    document.addEventListener('DOMContentLoaded', function() {
        loadCategories();
        loadProduct();
    });
</script>
<style>
    .form-group {
        margin-bottom: 20px;
    }

    .form-actions {
        margin-top: 30px;
        display: flex;
        gap: 10px;
    }

    .required {
        color: var(--error-color);
    }

    .image-preview-container {
        margin-top: 10px;
        max-width: 300px;
    }

    #imagePreview, #currentImage {
        width: 100%;
        border-radius: 4px;
        border: 1px solid var(--border-color);
    }

    #currentImageContainer {
        margin-top: 10px;
    }

    small {
        color: var(--text-secondary);
        display: block;
        margin-top: 5px;
    }

    .warning-text {
        color: #f0ad4e;
        font-weight: bold;
    }
</style>
</body>
</html> 